 
#include <string.h>
#include <math.h>
#include "system.h"
#include "f1c100s_de.h"
#include "f1c100s_timer.h"
#include "f1c100s_intc.h"
#include "f1c100s_gpio.h"
#include "f1c100s_pwm.h"
#include "f1c100s_uart.h"
#include "arm32.h"

void uart1_irq_handler(void);
void uart_irq_init();
void uart1_send_string(uint8_t tx[], uint32_t len);

#define MAX_RX_BUF 500
uint8_t rx_flag;
uint16_t index0 = 0;
uint8_t rx_data[MAX_RX_BUF];

int main(void)
{
    system_init();            // Initialize clocks, mmu, cache, uart, ...
    arm32_interrupt_enable(); // Enable interrupts
    uart_irq_init();
    printf("Hello, world. %s\r\n", __TIME__);

    while (1)
    {
        asm("nop");
        delay_soft(20);
        if (rx_flag)
        {
            rx_flag = 0;
            uart1_send_string(rx_data, index0 + 1);
            for (int i = 0; i < index0 + 1; i++)
            {
                rx_data[i] = 0;
            }
            index0 = 0;
        }
    }
}

void uart_irq_init()
{
    intc_enable_irq(IRQ_UART1);
    uart_enable_interrupt(UART1, UART_IEN_RBF);
    intc_set_irq_handler(IRQ_UART1, uart1_irq_handler);
}

void uart1_send_string(uint8_t tx[], uint32_t len)
{
    for (uint32_t i = 0; i < len; i++)
    {
        uart_tx(UART1, tx[i]);
    }
}

void uart1_irq_handler(void)
{
    uint32_t it_status = uart_get_status(UART1);
    if (it_status & UART_LSR_DR)
    {
        rx_flag = 1;
        rx_data[index0] = uart_get_rx(UART1);
        // uart_tx(UART1, rx_data);
        index0++;
        index0 = index0 % MAX_RX_BUF;
    }
}